import sys
from os.path import exists, dirname, join

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QWidget
from PyQt5.QtWidgets import QGraphicsBlurEffect

def set_blur_effect(widget: QWidget, back_label: QLabel, img_file: str, radius: int = 15):
    if not widget or not exists(img_file):
        return

    back_label.setGeometry(0, 0, widget.width(), widget.height())
    back_label.setStyleSheet("background-color: transparent;")

    pixmap = QPixmap(img_file).scaled(back_label.size())
    back_label.setPixmap(pixmap.scaled(back_label.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))

    blur_effect = QGraphicsBlurEffect(widget)
    blur_effect.setBlurRadius(radius)
    widget.setGraphicsEffect(blur_effect)



class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('毛玻璃效果窗口')
        self.setGeometry(100, 100, 600, 400)
        self.img_file = join(dirname(__file__), "res", "test.png")
        self.label = QLabel(self)
        set_blur_effect(self, self.label, self.img_file)

    def resizeEvent(self, a0):
        super().resizeEvent(a0)
        set_blur_effect(self, self.label, self.img_file)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())
